# -*- coding: utf-8 -*-
import asyncio
from bleak import BleakClient, BleakScanner
from bleak.backends.characteristic import BleakGATTCharacteristic
from time import sleep
import config

end_flag = False
constriction = 0
diastolic = 0
pulse = 0


def print_hex(bytes):
    l = [hex(int(i)) for i in bytes]
    return " ".join(l)


async def main():
    print("starting scan...")

    # 基于设备地址查找设备
    device = await BleakScanner.find_device_by_address(config.device_address)
    if device is None:
        print("could not find device with adderess '%s'", config.device_address)
        return

    print("connecting to device...")

    async with BleakClient(device) as client:
        print("connected")

        def notification_handler(sender, data):
            global end_flag
            global constriction
            global diastolic
            global pulse
            print(f"{sender}: {print_hex(data)}")
            if len(data) == 14:
                constriction = data[8] * 16 + data[9]
                diastolic = data[10] * 16 + data[11]
                pulse = data[12]
                end_flag = True

        await client.start_notify(config.notify_uuid, notification_handler)

        while not end_flag:
            await asyncio.sleep(1)

        await client.stop_notify(config.notify_uuid)
        print(f"接收收缩压: {constriction}")
        print(f"接收舒张压: {diastolic}")
        print(f"接收脉率: {pulse}")


if __name__ == "__main__":
    asyncio.run(main())